package com.rgzn.fzxj.service;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.rgzn.fzxj.config.RedisCache;
import com.rgzn.fzxj.config.WechatConfig;
import com.rgzn.fzxj.constants.CacheConstants;
import com.rgzn.fzxj.util.FileTransJavaDemo;
import com.rgzn.fzxj.util.OsChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    private static Logger logger = LoggerFactory.getLogger(TokenService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private RedisCache redisCache;


    public String getToken() {
        String accessToken = redisCache.getCacheObject(CacheConstants.ACCESS_TOKEN_KEY);
        if (ObjectUtil.isNull(accessToken)) {
            ResponseEntity<String> exchange = restTemplate.exchange(wechatConfig.getAccessTokenUrl(), HttpMethod.GET, null, String.class);
            if (exchange.getStatusCode().is2xxSuccessful()) {
                String body = exchange.getBody();
                JSONObject jsonObject = JSON.parseObject(body);
                accessToken = jsonObject.get("access_token").toString();
            }
            if (null == accessToken) {
                throw new RuntimeException("获取access_toke失败");
            }
            redisCache.setCacheObject(CacheConstants.ACCESS_TOKEN_KEY, accessToken, 1, TimeUnit.MINUTES);
        }
        logger.info("获取access_toke：{}", accessToken);
        return accessToken;
    }

    /**
     * 文本消息发送
     *
     * @param openId
     * @param content 回复内容
     * @return
     */
    public String sending(String openId, String content) {
        String requestUrl = String.format(wechatConfig.getCustomSendUrl(), getToken());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HashMap<String, Object> params = new HashMap<>();
        params.put("touser", openId);
        params.put("msgtype", "text");
        params.put("text", MapUtil.builder().put("content", content).build());
        HttpEntity<String> stringHttpEntity = new HttpEntity<>(JSON.toJSONString(params), headers);
        ResponseEntity<String> exchange = restTemplate.exchange(requestUrl, HttpMethod.POST, stringHttpEntity, String.class);
        logger.info("客服回复：{}", exchange);
        if (exchange.getStatusCode().is2xxSuccessful()) {
            String body = exchange.getBody();
            logger.info("客服回复异步回复：{}", body);
            return body;
        }
        return "";
    }

    public boolean sendingClassificationOfIssues(String openId, String content) {
        if (CollectionUtils.isEmpty(wechatConfig.getClassificationOfIssueDataList())) {
            logger.info("问题分类");
            return false;
        }
        boolean containsAny = wechatConfig.getClassificationOfIssueDataList().stream().anyMatch(content::contains);
        if (containsAny) {
            String requestUrl = String.format(wechatConfig.getCustomSendUrl(), getToken());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HashMap<String, Object> params = new HashMap<>();
            params.put("touser", openId);
            params.put("msgtype", "text");
            params.put("text", MapUtil.builder().put("content", wechatConfig.getReplyToTheContent()).build());
            HttpEntity<String> stringHttpEntity = new HttpEntity<>(JSON.toJSONString(params), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(requestUrl, HttpMethod.POST, stringHttpEntity, String.class);
            logger.info("问题分类客服回复：{}", exchange);
            return true;
        }
        return false;
    }

    public void sendingQcImage(String openId, String content) {
        if (CollectionUtils.isEmpty(wechatConfig.getVocabularyList())) {
            logger.info("词汇不能为空");
            return;
        }
        boolean containsAny = wechatConfig.getVocabularyList().stream().anyMatch(content::contains);
        if (!containsAny) {
            return;
        }
        String requestUrl = String.format(wechatConfig.getCustomSendUrl(), getToken());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HashMap<String, Object> params = new HashMap<>();
        params.put("touser", openId);
        params.put("msgtype", "image");
        params.put("image", MapUtil.builder().put("media_id", wechatConfig.getQrCodeImageMediaId()).build());
        HttpEntity<String> stringHttpEntity = new HttpEntity<>(JSON.toJSONString(params), headers);
        ResponseEntity<String> exchange = restTemplate.exchange(requestUrl, HttpMethod.POST, stringHttpEntity, String.class);
        logger.info("客服回复图片：{}", exchange);
        if (exchange.getStatusCode().is2xxSuccessful()) {
            String body = exchange.getBody();
            logger.info("客服回复异步图片：{}", body);
        }
    }


    private ResponseEntity<String> sendPostRequest(String url, Map<String, Object> params) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(params), headers);
        return restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
    }

    //调用微信提供的接口获取录音的InputStream字节流
    public String getMediaIdMp3Path(String mediaId) {
        String getVoiceAmrFile = String.format(wechatConfig.getGetVoiceAmrFile(), getToken(), mediaId);
        String tempPath = OsChecker.isLinux() ? wechatConfig.getAmrLinuxTemPath() : wechatConfig.getAmrWinTemPath();
        Path directoryPath = Paths.get(tempPath);

        try {
            Files.createDirectories(directoryPath);
        } catch (IOException e) {
            logger.error("无法创建目录 {}", directoryPath, e);
            return null;
        }

        try {
            String amrFilename = System.currentTimeMillis() + ".mp3";
            Path amrFilePath = directoryPath.resolve(amrFilename);
            logger.info("MP3 文件路径：{}", amrFilePath);

            HttpURLConnection connection = (HttpURLConnection) new URL(getVoiceAmrFile).openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                     FileOutputStream outputStream = new FileOutputStream(amrFilePath.toFile())) {

                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    return wechatConfig.getOnlineAddress() + amrFilename;
                }
            } else {
                logger.error("获取语音文件失败：响应代码 {}", connection.getResponseCode());
                return null;
            }
        } catch (Exception e) {
            logger.error("获取 mediaId 为 {} 的媒体时出错", mediaId, e);
            return null;
        }
    }


    public String getVoiceText(String mp3Url) {
        //String voiceUrl = "https://midp-1300467323.cos.ap-nanjing.myqcloud.com/midp%2Fvoice4745918292168364430.mp3";
        FileTransJavaDemo demo = new FileTransJavaDemo(wechatConfig.getAccessKeyId(), wechatConfig.getAccessKeySecret());
        String resultText = "";
        try {
            // 第一步：提交录音文件识别请求，获取任务ID用于后续的识别结果轮询。
            String taskId = demo.submitFileTransRequest(wechatConfig.getAppKey(), mp3Url);

            if (taskId == null) {
                logger.error("录音文件识别请求失败！");
                return resultText;
            }

            // 第二步：根据任务ID轮询识别结果。
            String result = demo.getFileTransResult(taskId);
            if (result == null) {
                logger.error("录音文件识别结果查询失败！");
                return resultText;
            }

            JSONArray voiceList = JSON.parseObject(result).getJSONArray("Sentences");
            if (voiceList != null && voiceList.size() > 0) {
                for (int i = 0; i < voiceList.size(); i++) {
                    resultText += voiceList.getJSONObject(i).getString("Text");
                }
                logger.info("录音文件识别结果: {}", resultText);
            } else {
                logger.warn("未找到任何语音识别结果。");
            }
        } catch (Exception e) {
            logger.error("处理语音识别请求时发生异常", e);
        }
        return resultText;
    }
}
